package com.itheima.appserver.service;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.StrUtil;
import com.alibaba.dubbo.config.annotation.Reference;
import com.github.tobato.fastdfs.domain.conn.FdfsWebServer;
import com.github.tobato.fastdfs.domain.fdfs.StorePath;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import com.itheima.appserver.excepiton.MyException;
import com.itheima.appserver.interceptor.UserThreadLocal;
import com.itheima.commons.constants.Constants;
import com.itheima.commons.model.domain.UserInfo;
import com.itheima.commons.model.mongo.FollowUser;
import com.itheima.commons.model.mongo.Video;
import com.itheima.commons.model.vo.ErrorResult;
import com.itheima.commons.model.vo.PageResult;
import com.itheima.commons.model.vo.VideoVo;
import com.itheima.dubbo.interfaces.VideoApi;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;

/**
 * 小视频业务类
 */
@Service
public class VideoService {

    @Reference
    private VideoApi videoApi;

    @Autowired
    protected FastFileStorageClient storageClient;

    @Autowired
    private FdfsWebServer fdfsWebServer;

    @Autowired
    private CommentsService commentsService;

    @Autowired
    private UserInfoService userInfoService;

    @Autowired
    private IdService idService;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    /**
     * 小视频上传
     *
     * @param picFile   封面图片
     * @param videoFile 视频文件
     * @return
     */
    public void saveVideo(MultipartFile picFile, MultipartFile videoFile) {
        // 先判断小视频的文件是否为空 如果为空就直接抛出"一个小视频内容不能为空"的异常
        // 判断 小视频 和  封面图片的 格式
        // 判断 小视频 和  封面图片的 大小
        // 把图片 和 小视频 上传到FastDFS中
        // 先上传封面图片文件  这个地方我没有校验
        try {
            StorePath picPath = this.storageClient.uploadFile(picFile.getInputStream(), picFile.getSize(), StrUtil.subAfter(picFile.getOriginalFilename(), ".", true), null);
            StorePath videoPath = this.storageClient.uploadFile(videoFile.getInputStream(), videoFile.getSize(), StrUtil.subAfter(videoFile.getOriginalFilename(), ".", true), null);

            Video video = new Video();
            // 主键ID
            video.setId(new ObjectId());
            // 用于大数据推荐的VID
            video.setVid(idService.createId("VIDEO"));
            // 上传小视频的人的ID
            video.setUserId(UserThreadLocal.getUserId());
            // 小视频的配文
            video.setText("可以不写");
            // 封面图片地址
            video.setPicUrl(fdfsWebServer.getWebServerUrl() + picPath.getFullPath());
            // 小视频地址
            video.setVideoUrl(fdfsWebServer.getWebServerUrl() + videoPath.getFullPath());
            // 发布时间
            video.setCreated(System.currentTimeMillis());
            // 调用Dubbo实现小视频的发布
            videoApi.saveVideo(video);
        } catch (Exception e) {
            throw new MyException(ErrorResult.uploadSmallVideoIsEmpty());
        }
    }

    /**
     * 小视频推荐列表
     *
     * @param page
     * @param pageSize
     * @return
     */
    public PageResult queryVideoList(Integer page, Integer pageSize) {
        // 从Redis中查询推荐的VID
        String vids = redisTemplate.opsForValue().get(Constants.VIDEOS_RECOMMEND + UserThreadLocal.getUserId());
        // 手动分页(逻辑分页)  推荐系统一般都是每隔几分钟执行一次运算
        List<Video> videos = Collections.emptyList();
        if (StrUtil.isBlank(vids)) {
            // 没有推荐数据 从MongoDB中随机抽查一些数据返回
            videos = videoApi.randomVideos(pageSize);
        } else {
            // [124,188,87,145,176,93,69,161,40,140,193,88,117,182,122,199,4,141,103,160]
            List<String> vidList = StrUtil.split(vids, ",");
            // 手动分页
            int startIndex = (page - 1) * pageSize;
            // 当前页要显示的小视频的VID
            List<String> vidIdList = CollUtil.sub(vidList, startIndex, Math.min(startIndex + pageSize, vidList.size()));

            // 根据redis中的pid查询到的圈子详情
            videos = videoApi.findVideosByVids(Convert.toList(Long.class, vidIdList));
        }

        // 查询发布人的信息
        // 从上面的结果集中提取发布人的id
        List<Long> userIds = CollUtil.getFieldValues(videos, "userId", Long.class);
        // 根据上面的这个用户id集合去查询他们的详细信息
        Map<Long, UserInfo> userInfoMap = userInfoService.findUserInfoListByUserIds(null, userIds);
        // 拼凑VO对象
        List<VideoVo> videosVoList = new ArrayList<>();
        for (Video vv : videos) {
            VideoVo videoVo = new VideoVo();
            videoVo.setId(vv.getId().toHexString());
            videoVo.setCover(vv.getPicUrl());
            videoVo.setVideoUrl(vv.getVideoUrl());
            videoVo.setSignature("");

            UserInfo userInfo = userInfoMap.get(vv.getUserId());
            videoVo.setUserId(userInfo.getUserId());
            videoVo.setAvatar(userInfo.getLogo());
            videoVo.setNickname(userInfo.getNickName());

            // 点赞数
            videoVo.setLikeCount(Convert.toInt(commentsService.queryVideoLikeCount(vv.getId().toHexString())));
            // 是否点赞
            videoVo.setHasLiked(commentsService.queryUser2VideoIsLike(vv.getId().toHexString()) ? 1 : 0);
            // 是否关注
            videoVo.setHasFocus(redisTemplate.opsForSet().isMember(Constants.VIDEO_FOLLOW_HASHKEY + UserThreadLocal.getUserId(), userInfo.getUserId().toString()) ? 1 : 0);
            // 评论数
            videoVo.setCommentCount(Convert.toInt(commentsService.queryVideoCommentCount(vv.getId().toHexString())));

            videosVoList.add(videoVo);
        }

        // 返回的VO对象
        PageResult pageResult = new PageResult(page, pageSize, 0L, videosVoList);
        return pageResult;
    }

    /**
     * 小视频点赞
     *
     * @param videoId
     * @return
     */
    public Long likeComment(String videoId) {
        return commentsService.videoLike(videoId);
    }

    /**
     * 小视频取消点赞
     *
     * @param videoId
     * @return
     */
    public Long disLikeComment(String videoId) {
        return commentsService.cancelVideoLike(videoId);
    }

    /**
     * 小视频文本评论
     *
     * @param videoId
     * @param content
     * @return
     */
    public void saveComment(String videoId, String content) {
        commentsService.videoComment(videoId, content);
    }

    /**
     * 小视频评论列表
     *
     * @param videoId
     * @param page
     * @param pageSize
     * @return
     */
    public PageResult queryCommentList(String videoId, Integer page, Integer pageSize) {
        return commentsService.queryCommentList(videoId, page, pageSize);
    }

    /**
     * 关注用户
     *
     * @param userId
     * @return
     */
    public void followUser(Long userId) {
        FollowUser followUser = new FollowUser();
        followUser.setId(new ObjectId());
        followUser.setUserId(UserThreadLocal.getUserId());
        // 传递过来的userId是主播的ID
        followUser.setFollowUserId(userId);
        followUser.setCreated(System.currentTimeMillis());

        videoApi.followUser(followUser);

        // 把关注的人的id缓存到Redis中
        redisTemplate.opsForSet().add(Constants.VIDEO_FOLLOW_HASHKEY + UserThreadLocal.getUserId(), userId.toString());
    }

    /**
     * 取消关注
     *
     * @param userId
     * @return
     */
    public void disFollowUser(Long userId) {
        videoApi.disFollowUser(UserThreadLocal.getUserId(), userId);
        // 从redis中删除取消关注的人
        redisTemplate.opsForSet().remove(Constants.VIDEO_FOLLOW_HASHKEY + UserThreadLocal.getUserId(), userId.toString());
    }
}